package com.kamkor.interviewer.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.kamkor.interviewer.client.InterviewServiceAsync;
import com.kamkor.interviewer.client.Interviewer;
import com.kamkor.interviewer.client.security.Authentication;

/**
 * 
 * @author kamkor
 *
 */
public class InterviewInfoPresenter extends SecuredPresenter {	
	private final InterviewServiceAsync service;
	private final Display display;
	private final HandlerManager eventBus;
	private Long interviewId;
	
	/** Interviewer key */
	private Long adminKey;
	
	/** Interviewed key */
	private Long userKey;
	
	public interface Display {		
		TextArea getInterviewInformation();
		HasClickHandlers getSelectAll();
		HasClickHandlers getEditInterview();	
		Widget asWidget();		
	}
	
	public InterviewInfoPresenter(InterviewServiceAsync service, Display display, HandlerManager eventBus, 
			Long interviewId, Long adminKey, Long userKey, Authentication authentication) {
		super(authentication, interviewId, adminKey);
		this.service = service;
		this.display = display;
		this.eventBus = eventBus;
		this.interviewId = interviewId;
		this.adminKey = adminKey;		
		this.userKey = userKey;
	}
	
	public void bind() {		
		final String adminHistoryToken = "editInterview&" + "i=" + interviewId + "&k=" + adminKey;
		final String userHistoryToken = "answerInterview&" + "i=" + interviewId + "&k=" + userKey;
		
		final String interviewAdminUrl = GWT.getHostPageBaseURL() + "#" + adminHistoryToken;
		final String interviewUserUrl = GWT.getHostPageBaseURL() + "#" + userHistoryToken;
		
		final String interviewerLinkDescription = Interviewer.constants.linkForInterviewer() + " ";
		final String interviewedLinkDescription = Interviewer.constants.linkForInterviewed() + " ";
		
		display.getInterviewInformation().setText(
				interviewerLinkDescription + interviewAdminUrl + "\n" + 
				interviewedLinkDescription + interviewUserUrl);	
		
		display.getSelectAll().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				display.getInterviewInformation().selectAll();				
			}
		});
		
		display.getEditInterview().addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				History.newItem(adminHistoryToken);
			}
		});		
	}

	@Override
	public void authenticationFailed() {

	}

	@Override
	protected void goAuthenticated(HasWidgets container) {
		bind();
		container.clear();	
		container.add(display.asWidget());			
	}
}
